import mongoengine
from log import log
from config import config
from diskcache import Cache,FanoutCache

#数据库

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]


class MyDb(metaclass=Singleton):
    def __init__(self):
        try:
            mongoengine.connect(config["cmsname"], host=config["dbhost"], port=config["dbport"], maxPoolSize=50, waitQueueMultiple=10)
            self.mongos = mongoengine
        except IOError:
            log.error("err connect db",IOError.errno)
        else:
            log.info("db connect success")

    def getSession(self):
        return self.mongos

    def close(self):
        # pass
        self.mongos.connection.disconnect()

class MyCache(metaclass=Singleton):
    def __init__(self):
        self.cache = Cache("/tmp")
        self.fCache = FanoutCache("/tmp/dao")

    def session(self)->Cache:
        return self.cache

    def fsession(self)->FanoutCache:
        return self.fCache